<?php


/**
 * Notes:
 * PROJECT_NAME : ERP v1.8 重构erp
 * User: 夏鱼儿<397072174@qq.com>
 * Date: 2024/3/13
 * Time: 17:46
 */

namespace app\admin\model;

use think\db\exception\DbException;
use think\Model;

/**
 * @property  int $id
 * @property  int $status
 * @property  int $goods_id
 */
class GoodsRule extends BaseModel
{

    /**
     * 监听商品规则更新
     * @param GoodsRule $model
     * @return void
     * @throws DbException
     */
    public static function onAfterUpdate(GoodsRule $model): void
    {
        if ($model->status == 2) {
            if(!GoodsRule::where('goods_id', $model->goods_id)->where('status',1)->count()){
                //更改商品状态
                Goods::where('id', $model->goods_id)->update(['status' => 2]);
            }
        }
        if ($model->status == 1) {
            Goods::where('id', $model->goods_id)->update(['status' => 1]);
        }
    }

    /**
     * 删除事件
     * @param GoodsRule $model
     * @return void
     * @throws DbException
     */
    public static function onBeforeDelete(GoodsRule $model): void
    {
        if(!GoodsRule::where('goods_id', $model->goods_id)->whereNotIn('id',$model->id)->count()){
            //删除商品
            Goods::destroy($model->goods_id);
        }
    }
}